import defaultValue from "./defaultValue.js";
import defined from "./defined.js";
import clone from "./clone";

/**
 * Merges two objects, copying their properties onto a new combined object. When two objects have the same
 * property, the value of the property on the first object is used.  If either object is undefined,
 * it will be treated as an empty object.
 *
 * @example
 * var object1 = {
 *     propOne : 1,
 *     propTwo : {
 *         value1 : 10
 *     }
 * }
 * var object2 = {
 *     propTwo : 2
 * }
 * var final = Cesium.combine(object1, object2);
 *
 * // final === {
 * //     propOne : 1,
 * //     propTwo : {
 * //         value1 : 10
 * //     }
 * // }
 *
 * @param {Object} [object1] The first object to merge. not null
 * @param {Object} [object2] The second object to merge.
 * @param {Boolean} [deep=false] Perform a recursive merge.
 * @returns {Object} The merged object containing all properties from both objects.
 *
 * @function
 */
function merge(object1, object2, deep) { // object2 覆盖 object1

  deep = defaultValue(deep, false);

  var result = clone(object1, deep);

  const object2Defined = defined(object2);

  var property;
  var object1Value;
  var object2Value;
  if (object2Defined) {
    if(!result){
      result = new object2.constructor();
      return clone(object2, deep);
    }
    for (property in object2) {
      if (object2.hasOwnProperty(property)) {
        object1Value = result[property];
        object2Value = object2[property];
        if (typeof object1Value === "object" && typeof object2Value === "object"){
          result[property] =  merge(object1Value, object2Value, deep);
        }else{
          result[property] =  clone(object2Value, deep);
        }
      }
    }
  }
  return result;
}
export default merge;
